package com.qqim.client.ui;

import com.qqim.client.ClientMain;
import com.qqim.client.network.NetworkManager;
import com.qqim.common.entity.User;
import com.qqim.common.protocol.Protocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * 登录对话框
 */
public class LoginDialog extends JDialog implements NetworkManager.MessageListener {
    private static final Logger logger = LoggerFactory.getLogger(LoginDialog.class);
    
    private final ClientMain clientMain;
    private JTextField hostField;
    private JTextField portField;
    private JTextField userIdField;
    private JTextField nicknameField;
    private JButton connectButton;
    private JButton loginButton;
    private JLabel statusLabel;
    
    private boolean connected = false;
    
    public LoginDialog(ClientMain clientMain) {
        super((Frame) null, "QQ即时通信 - 登录", true);
        this.clientMain = clientMain;
        
        initComponents();
        layoutComponents();
        bindEvents();
        
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setSize(400, 300);
        setLocationRelativeTo(null);
        setResizable(false);
        
        // 设置消息监听器
        clientMain.getNetworkManager().setMessageListener(this);
    }
    
    private void initComponents() {
        hostField = new JTextField("localhost");
        portField = new JTextField("8888");
        
        // 自动生成唯一ID和随机名称
        String autoUserId = generateUniqueUserId();
        String autoNickname = generateRandomNickname();
        
        userIdField = new JTextField(autoUserId);
        nicknameField = new JTextField(autoNickname);
        
        connectButton = new JButton("连接服务器");
        loginButton = new JButton("登录");
        loginButton.setEnabled(false);
        
        statusLabel = new JLabel("请先连接服务器");
        statusLabel.setForeground(Color.RED);
    }
    
    /**
     * 生成唯一用户ID
     */
    private String generateUniqueUserId() {
        // 使用时间戳 + 随机数确保唯一性
        long timestamp = System.currentTimeMillis();
        int random = new Random().nextInt(1000);
        return String.valueOf(timestamp % 1000000) + String.format("%03d", random);
    }
    
    /**
     * 生成随机昵称
     */
    private String generateRandomNickname() {
        // 一些有趣的昵称前缀
        String[] prefixes = {
            "小萌", "酷炫", "可爱", "神秘", "快乐", "温暖", "阳光", "梦想",
            "星空", "彩虹", "月亮", "蓝天", "花花", "甜心", "天使", "精灵"
        };
        
        // 昵称后缀
        String[] suffixes = {
            "用户", "宝贝", "小仙女", "大神", "达人", "玩家", "朋友", "小伙伴",
            "探索者", "冒险家", "梦想家", "艺术家", "设计师", "程序员", "学霸", "才子"
        };
        
        Random random = new Random();
        String prefix = prefixes[random.nextInt(prefixes.length)];
        String suffix = suffixes[random.nextInt(suffixes.length)];
        
        // 添加随机数字使名称更独特
        int number = random.nextInt(999) + 1;
        
        return prefix + suffix + String.format("%03d", number);
    }
    
    private void layoutComponents() {
        setLayout(new BorderLayout());
        
        // 标题
        JLabel titleLabel = new JLabel("QQ即时通信", JLabel.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 20));
        titleLabel.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));
        
        // 输入面板
        JPanel inputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        
        gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.EAST;
        inputPanel.add(new JLabel("服务器地址:"), gbc);
        gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        inputPanel.add(hostField, gbc);
        
        gbc.gridx = 0; gbc.gridy = 1; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0;
        inputPanel.add(new JLabel("端口:"), gbc);
        gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        inputPanel.add(portField, gbc);
        
        gbc.gridx = 0; gbc.gridy = 2; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0;
        inputPanel.add(new JLabel("用户ID:"), gbc);
        gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        inputPanel.add(userIdField, gbc);
        
        gbc.gridx = 0; gbc.gridy = 3; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0;
        inputPanel.add(new JLabel("昵称:"), gbc);
        gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0;
        inputPanel.add(nicknameField, gbc);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(connectButton);
        buttonPanel.add(loginButton);
        
        // 状态面板
        JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        statusPanel.add(statusLabel);
        
        // 底部面板 - 包含按钮和状态
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.add(buttonPanel, BorderLayout.CENTER);
        bottomPanel.add(statusPanel, BorderLayout.SOUTH);
        
        add(titleLabel, BorderLayout.NORTH);
        add(inputPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
    }
    
    private void bindEvents() {
        connectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                connectToServer();
            }
        });
        
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                login();
            }
        });
    }
    
    private void connectToServer() {
        String host = hostField.getText().trim();
        String portStr = portField.getText().trim();
        
        if (host.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入服务器地址", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        try {
            int port = Integer.parseInt(portStr);
            
            statusLabel.setText("正在连接服务器...");
            statusLabel.setForeground(Color.BLUE);
            
            boolean success = clientMain.getNetworkManager().connect(host, port);
            
            if (success) {
                connected = true;
                statusLabel.setText("服务器连接成功");
                statusLabel.setForeground(Color.GREEN);
                
                connectButton.setEnabled(false);
                loginButton.setEnabled(true);
                hostField.setEnabled(false);
                portField.setEnabled(false);
            } else {
                statusLabel.setText("连接服务器失败");
                statusLabel.setForeground(Color.RED);
            }
            
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "端口必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void login() {
        String userId = userIdField.getText().trim();
        String nickname = nicknameField.getText().trim();
        
        if (userId.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入用户ID", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        if (nickname.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入昵称", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        // 防止重复点击 - 禁用登录按钮
        loginButton.setEnabled(false);
        statusLabel.setText("正在登录...");
        statusLabel.setForeground(Color.BLUE);
        
        boolean success = clientMain.getNetworkManager().login(userId, nickname);
        if (!success) {
            statusLabel.setText("发送登录请求失败");
            statusLabel.setForeground(Color.RED);
            // 重新启用登录按钮
            loginButton.setEnabled(true);
        }
    }
    
    @Override
    public void onMessageReceived(Protocol protocol) {
        SwingUtilities.invokeLater(() -> {
            switch (protocol.getType()) {
                case Protocol.LOGIN_SUCCESS:
                    handleLoginSuccess(protocol);
                    break;
                    
                case Protocol.LOGIN_FAILED:
                    handleLoginFailed(protocol);
                    break;
                    
                case Protocol.USER_LIST:
                    handleUserList(protocol);
                    break;
            }
        });
    }
    
    @Override
    public void onConnectionLost() {
        SwingUtilities.invokeLater(() -> {
            statusLabel.setText("连接已断开");
            statusLabel.setForeground(Color.RED);
            
            connectButton.setEnabled(true);
            loginButton.setEnabled(false);
            hostField.setEnabled(true);
            portField.setEnabled(true);
            connected = false;
        });
    }
    
    private void handleLoginSuccess(Protocol protocol) {
        String userId = userIdField.getText().trim();
        String nickname = nicknameField.getText().trim();
        
        User user = new User(userId, nickname);
        clientMain.getCacheManager().setCurrentUser(user);
        
        // 显示主窗口
        new MainWindow(clientMain).setVisible(true);
        
        // 关闭登录窗口
        dispose();
    }
    
    private void handleLoginFailed(Protocol protocol) {
        String errorMessage = protocol.getErrorMessage();
        statusLabel.setText("登录失败: " + errorMessage);
        statusLabel.setForeground(Color.RED);
        
        // 重新启用登录按钮
        loginButton.setEnabled(true);
        
        JOptionPane.showMessageDialog(this, errorMessage, "登录失败", JOptionPane.ERROR_MESSAGE);
    }
    
    @SuppressWarnings("unchecked")
    private void handleUserList(Protocol protocol) {
        Map<String, Object> rawUsers = (Map<String, Object>) protocol.getData();
        Map<String, User> users = new HashMap<>();
        
        // 将LinkedTreeMap转换为User对象
        for (Map.Entry<String, Object> entry : rawUsers.entrySet()) {
            String userId = entry.getKey();
            
            if (entry.getValue() instanceof Map) {
                Map<String, Object> userMap = (Map<String, Object>) entry.getValue();
                
                User user = new User();
                user.setUserId((String) userMap.get("userId"));
                user.setNickname((String) userMap.get("nickname"));
                user.setStatus((String) userMap.get("status"));
                
                if (userMap.get("loginTime") instanceof Number) {
                    user.setLoginTime(((Number) userMap.get("loginTime")).longValue());
                }
                if (userMap.get("lastActiveTime") instanceof Number) {
                    user.setLastActiveTime(((Number) userMap.get("lastActiveTime")).longValue());
                }
                
                users.put(userId, user);
            }
        }
        
        clientMain.getCacheManager().updateOnlineUsers(users);
    }
} 